<template>
  <a-menu @click="handlerMenu" v-model:openKeys="state.openKeys" v-model:selectedKeys="selectedKeys" mode="inline" :inline-collapsed="!fixed ? collapse : false">
    <template v-for="item in items" :key="item.key">
      <template v-if="!item?.meta?.hidden">
        <a-menu-item :key="item.path">
          <template #icon>
            <i v-if="item?.meta?.icon" class="iconfont" :class="item.meta.icon"></i>
          </template>
          <span>{{ item?.meta?.title }}</span>
        </a-menu-item>
        <!-- <sub-menu v-else :menu="item" /> -->
      </template>
    </template>
  </a-menu>
</template>
<script setup>
  import { reactive, computed, watch, onMounted } from "vue"
  import { useRouter } from "vue-router"
  // hook
  import { useCollaps } from "@/hook/index"
  const { useGetCollasp } = useCollaps()
  const collapse = computed(() => useGetCollasp())
  const props = defineProps({
    fixed: Boolean,
  })
  /**
   * router
   */
  const router = useRouter()
  const items = reactive(router.options.routes)
  /**
   * state
   */
  const state = reactive({
    openKeys: [],
    keepAlivePath: null,
  })
  const openKeys = () => {
    const key = router.currentRoute.value.matched[0]?.path
    state.openKeys = [key.substring(1)]
  }
  const selectedKeys = computed(() => {
    const currentPath = router.currentRoute.value
    let key = currentPath.matched[0]?.path
    return [key]
  })
  /**
   * 获取最后一层路由的第1个子级
   */
  const getLastRouerChildren = (routerInfo) => {
    let childrenRouter = routerInfo?.children?.[0]
    // 是否存在下一层
    if (childrenRouter.children && childrenRouter.children.length) {
      childrenRouter = childrenRouter.children[0]
    }
    return childrenRouter
  }
  /**
   * handlerMenu
   */
  const handlerMenu = (val) => {
    // 是否有缓存path
    const routerInfo = router.getRoutes().filter((item) => item.path === val.key)[0]
    let keepAlivePath = null
    if (routerInfo.meta && routerInfo.meta.keepAlivePath) {
      keepAlivePath = routerInfo.meta.keepAlivePath
    }
    // 路由
    const path = keepAlivePath || getLastRouerChildren(routerInfo).path
    router.push({ path })
  }
  /**
   * 是否点击的同一个菜单
   */
  const checkSameRouter = (router) => {
    const localRouter = localStorage.getItem("sr")
    localStorage.setItem("sr", router)
    localStorage.setItem("sra", localRouter === router)
  }
  onMounted(() => {
    openKeys()
  })
</script>
